<?php

use app\models\Agent;
use app\models\AgentAccount;
use yii\db\Migration;

/**
 * Class m190602_060247_create_agent_account
 */
class m190602_060247_create_agent_account extends Migration
{
    /**
     * {@inheritdoc}
     */
    public function safeUp()
    {
        $this->createTable('{{%agent_account}}', [
            'id' => $this->primaryKey(),
            'agent_id' => $this->integer()->notNull()->comment('代理商编号'),
            'money' => $this->decimal(12, 2)->notNull()->defaultValue(0)->comment('现金余额'),
        ]);
        $this->createIndex('fk_agent_account_agent1_idx', '{{%agent_account}}', ['agent_id']);
        try {
            $this->addForeignKey('fk_agent_account_agent1', '{{%agent_account}}', ['agent_id'], '{{%agent}}', ['id']);
        } catch (Exception $e) {
            Yii::error($e->getMessage());
        }
        /** @var Agent $agent */
        foreach (Agent::find()->each() as $agent) {
            if (AgentAccount::find()->andWhere(['agent_id' => $agent->id])->exists()) {
                continue;
            }
            $account = new AgentAccount();
            $account->agent_id = $agent->id;
            $account->save();
        }
    }

    /**
     * {@inheritdoc}
     */
    public function safeDown()
    {
        $this->dropTable('{{%agent_account}}');
    }
}
